import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';
interface PropsT {
  listData: (string | number)[];
  time: number;
}
const Index: React.FC<PropsT> = (props) => {
  const { listData, time = 2000 } = props;

  const ulRef = useRef(null);
  const [timer, setTimer] = useState<any>();
  const [isRoll, setIsRoll] = useState<boolean>(true);
  const [childTran, setChildTran] = useState<number>(0);
  const [dataArr, setDataArr] = useState<any[]>([]);

  const rollHandler = () => {
    const hight = 22;
    let index = 0;
    if (isRoll) {
      const newTimer = setInterval(() => {
        console.log(listData.length * hight);
        index++;
        const newChildTran = index * hight;
        if (newChildTran >= listData.length * hight) {
          // 回到最初的位置
          index = 0;
          setChildTran(0);
        } else {
          setChildTran(newChildTran);
        }
      }, time);
      setTimer(newTimer);
    } else {
      clearInterval(timer);
    }
  };

  console.log('childTran', childTran);

  useEffect(() => {
    rollHandler();
    return clearInterval(timer);
  }, [dataArr, isRoll, time]);

  useEffect(() => {
    const newDataArr = [...listData];
    if (listData.length > 0) {
      // 将第一个元素追加到当前数组的后面 防止后面滚动衔接的时候空白
      newDataArr.push(listData[0]);
    }
    setDataArr(listData);
  }, [listData]);
  return (
    <div className={styles.myCarouselWrapper}>
      <ul
        className={styles.fllil}
        ref={ulRef}
        style={{
          transform: `translate3D(0px,-${childTran}px,0px)`,
        }}
        onMouseOver={() => setIsRoll(false)}
        onMouseLeave={() => setIsRoll(true)}
      >
        {dataArr.map((item, index) => {
          return <li key={index}>{item}</li>;
        })}
      </ul>
    </div>
  );
};

export default Index;
